package com.faryangsh.algorithm.basicfor1;

import java.util.Iterator;

/**
 * 1.3.2.5 加有迭代器的栈
 * <p>
 * Created by 杨志远 on 2017/8/13
 * email faryangsh@163.com.
 */
public class ResizingArrayStack<T> {
    int size;
    int forawardIndex;
    T[] items;

    public void ResizingArrayStack(int size) {
        items = (T[]) new Object[size];
    }

    public T pop() {
        if (forawardIndex > 0 && forawardIndex == size / 4) resize(size / 2);
        T item = items[--forawardIndex];
        //让游离的元素被java垃圾回收器回收
        items[forawardIndex] = null;
        return item;
    }

    public void push(T t) {
        if (forawardIndex == size) resize(2 * size);
        items[forawardIndex++] = t;
    }


    public void resize(int resize) {
        T[] temp = (T[]) new Object[resize];
        for (int i = 0; i < size; i++) temp[i] = items[i];
        items = temp;
        size = resize;
    }

    public Iterator<T> iterator() {
        return new ReverseArrayIterator();
    }

    private class ReverseArrayIterator implements Iterator<T> {
        //支持后进先出迭代

        private int i = forawardIndex;

        @Override
        public boolean hasNext() {
            return i > 0;
        }

        @Override
        public T next() {
            return items[--i];
        }
    }
}
